package com.informationsystem.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.informationsystem.service.DepartmentManager;
import com.informationsystem.dao.SearchException;
import com.informationsystem.model.Department;
import com.informationsystem.webapp.action.BaseAction;

import java.util.List;

public class DepartmentAction extends BaseAction implements Preparable {
    private DepartmentManager departmentManager;
    private List departments;
    private Department department;
    private Long id;
    private String query;

    public void setDepartmentManager(DepartmentManager departmentManager) {
        this.departmentManager = departmentManager;
    }

    public List getDepartments() {
        return departments;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String departmentId = getRequest().getParameter("department.id");
            if (departmentId != null && !departmentId.equals("")) {
                department = departmentManager.get(new Long(departmentId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        try {
            departments = departmentManager.search(query, Department.class);
        } catch (SearchException se) {
            addActionError(se.getMessage());
            departments = departmentManager.getAll();
        }
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public String delete() {
        departmentManager.remove(department.getId());
        saveMessage(getText("department.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            department = departmentManager.get(id);
        } else {
            department = new Department();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (department.getId() == null);

        departmentManager.save(department);

        String key = (isNew) ? "department.added" : "department.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}